<?php

namespace App\Backend\Service;

use AlibabaCloud\SDK\Green\V20220302\Green;
use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
#use Illuminate\Support\Facades\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

use Darabonba\OpenApi\Models\Config;

use Exception;
use Illuminate\Support\Facades\Log;
use App\Backend\Service\BaseService;
class ContentModerationService extends BaseService
{
    protected $client;

    public function __construct()
    {
        $config = new Config([
            'accessKeyId' => config('aliyun.access_key_id'),
            'accessKeySecret' => config('aliyun.access_key_secret'),
            'regionId' => config('aliyun.region_id'),
            "endpoint" => config('aliyun.oss.endpoint'),
            'connectTimeout' => 5000,
            'timeout' => 10000,
        ]);

        $this->client = new Green($config);
    }

    /**
     * 使用图片URL进行内容安全审核（高级版）
     *
     * @param string $imageUrl 图片URL
     * @return array|null
     */
    public function checkImageAdvanced($imageUrl)
    {
        $request = new ImageModerationRequest([
            'service' => 'image_advanced', // 高级图片检测
            'serviceParameters' => json_encode([
                'imageUrl' => $imageUrl,
                'scenes' => [config('aliyun.green.scene')]
            ])
        ]);

        try {
            $response = $this->client->imageModeration($request);
            return $response->body->toMap();
        } catch (Exception $error) {
            // 处理阿里云特定错误
            if ($error instanceof TeaError) {
                Log::error('阿里云内容安全检测失败', [
                    'code' => $error->getCode(),
                    'message' => $error->getMessage(),
                    'data' => $error->getData(),
                ]);
            } else {
                Log::error('内容安全检测异常: ' . $error->getMessage());
            }
            
            return null;
        }
    }

    /**
     * 获取OSS图片完整URL
     *
     * @param string $path OSS路径
     * @return string
     */
    public function getOssImageUrl($path)
    {
        $endpoint = config('aliyun.oss.endpoint');
        $bucket = config('aliyun.oss.bucket');
        
        return "https://{$bucket}.{$endpoint}/{$path}";
    }

    /**
     * 解析检测结果
     *
     * @param array $result 检测结果
     * @return array
     */
    public function parseResult($result)
    {
        if (!$result || $result['code'] !== 200) {
            $code=$result['code'] ?? 500;
            $msg="{$code}检测服务不可用";
            $this->error($msg);
        }

        $data = $result['data'][0] ?? null;
        if (!$data) {
            $this->error('无效的检测结果');
        }

        $suggestion = $data['suggestion'] ?? 'unknown';
        $label = $data['label'] ?? 'unknown';
        $confidence = $data['confidence'] ?? 0;

        $statusMap = [
            'pass' => 'safe',
            'review' => 'review',
            'block' => 'blocked'
        ];

        $status = $statusMap[$suggestion] ?? 'unknown';

        $msg=[
            'status' => $status,
            'suggestion' => $suggestion,
            'label' => $label,
            'confidence' => $confidence,
            'details' => $data
        ];

        return $msg;
    }
}
